<template>
  <div>
    <el-container>
      <el-header>
        <el-row :gutter="2" style="font-size: 12px">
          <el-col :span="4"></el-col>
          <el-col :span="2" :offset="8">
            <div class="t">欢迎登录:{{ username }}</div>
          </el-col>
          <el-col :span="4">
            <div class="t">
              <i class="el-icon-time"></i>
              &ensp;
              <span style="display: inline-block"><MyNowTime></MyNowTime></span>
            </div>
          </el-col>
          <el-col :span="2">
            <div class="t" @click="faceScanOpen">
              <i class="el-icon-camera"></i>
              &ensp;人脸注册
            </div>
          </el-col>
          <el-col :span="2">
            <div class="t" @click="upDatePassword">
              <i class="el-icon-setting"></i>
              &ensp;修改密码
            </div>
          </el-col>
          <el-col :span="2">
            <div class="t" @click="logout">
              <i class="el-icon-switch-button"></i>
              &ensp;退出登录
            </div>
          </el-col>
        </el-row>
      </el-header>
      <el-container>
        <el-aside
          width="200px"
          style="
            background-color: rgb(238, 241, 246);
            overflow: auto;
            height: 100%;
          "
        >
          <el-menu :unique-opened="true">
            <!-- :default-openeds="['1', '3']" -->

            <!-- 
            <el-submenu index="1">
              <template slot="title"
                ><i class="el-icon-user"></i>用户管理</template
              >
           
              
              <el-menu-item
                v-has="'ROLE_admin'"
                index="1-2"
                @click="$router.push('/adduser')"
                >添加用户</el-menu-item
              >
              
            </el-submenu>
             -->
            <el-menu-item index="1-1" @click="$router.push('/user')">
              <i class="el-icon-user"></i>
              用户查询
            </el-menu-item>

            <el-submenu index="2">
              <template slot="title">
                <i class="el-icon-setting"></i>
                部门管理
              </template>
              <el-menu-item index="2-1" @click="$router.push('/bumen')"
                >部门查询</el-menu-item
              >
              <el-menu-item
                v-has="'ROLE_admin'"
                index="2-2"
                @click="$router.push('/addbumen')"
              >
                部门添加
              </el-menu-item>
            </el-submenu>
            <el-submenu index="3">
              <template slot="title">
                <i class="el-icon-data-line"></i>
                职位管理
              </template>
              <el-menu-item index="3-1" @click="$router.push('/zhiwei')"
                >职位查询</el-menu-item
              >
              <el-menu-item
                v-has="'ROLE_admin'"
                index="3-2"
                @click="$router.push('/addzhiwei')"
              >
                添加职位
              </el-menu-item>
            </el-submenu>

            <el-submenu index="4">
              <template slot="title">
                <i class="el-icon-message"></i>
                公告管理
              </template>
              <el-menu-item index="4-1" @click="$router.push('/gonggao')"
                >公告查询</el-menu-item
              >
              <el-menu-item
                v-has="'ROLE_admin'"
                index="4-2"
                @click="$router.push('/addgonggao')"
              >
                添加公告
              </el-menu-item>
            </el-submenu>
            <el-submenu index="5">
              <template slot="title">
                <i class="el-icon-document"></i>
                下载中心
              </template>
              <el-menu-item index="5-1" @click="$router.push('/file')"
                >文档查询</el-menu-item
              >
              <el-menu-item index="5-2" @click="$router.push('/addfile')"
                >上传文档</el-menu-item
              >
            </el-submenu>
            <el-submenu index="9">
              <template slot="title">
                <i class="el-icon-document"></i>
                请假管理
              </template>
              <el-menu-item index="9-1" @click="$router.push('/leave')"
                >请假查询</el-menu-item
              >
              <el-menu-item index="9-2" @click="$router.push('/addLeave')"
                >请假申请</el-menu-item
              >
              <el-menu-item
                index="9-3"
                v-has="'ROLE_admin'"
                @click="$router.push('/leaveApproval')"
              >
                请假审批
              </el-menu-item>
            </el-submenu>
            <el-submenu v-has="'ROLE_admin'" index="7">
              <template slot="title">
                <i class="el-icon-s-custom"></i>
                员工管理
              </template>
              <el-menu-item
                v-has="'ROLE_admin'"
                index="7-1"
                @click="$router.push('/employeeInf')"
              >
                员工查询
              </el-menu-item>
              <el-menu-item
                v-has="'ROLE_admin'"
                index="7-2"
                @click="$router.push('/signInInf')"
              >
                考勤记录
              </el-menu-item>
              <!--     <el-menu-item index="7-3" @click="$router.push('/employee')">职位与薪资</el-menu-item> -->
              <el-menu-item
                index="7-3"
                v-has="'ROLE_admin'"
                @click="$router.push('/adduser')"
              >
                新人入队
              </el-menu-item>
            </el-submenu>
            <!--
            <el-submenu index="6">
              <template slot="title"
                ><i class="el-icon-document"></i>留言面板</template
              >
           
             <el-menu-item index="6-2">留言管理</el-menu-item> 
            </el-submenu>-->
            <el-menu-item index="6-1" @click="$router.push('/liuyan')">
              <i class="el-icon-document"></i>
              留言墙
            </el-menu-item>

            <!-- <el-submenu v-has="'ROLE_admin'" index="8">
              <template slot="title"
                ><i class="el-icon-document"></i>薪资管理</template
              >
            
            </el-submenu> -->
            <el-menu-item
              v-has="'ROLE_admin'"
              index="8-1"
              @click="$router.push('/salary')"
            >
              <i class="el-icon-document"></i>
              薪资管理
            </el-menu-item>

            <!-- <el-submenu index="10" v-has="'ROLE_admin'">
              <template slot="title"
                ><i class="el-icon-s-flag"></i>新人入队</template
              >
           
            </el-submenu> -->
            <!-- <el-menu-item
              v-has="'ROLE_admin'"
              index="10-1"
              @click="$router.push('/adduser')"
              ><i class="el-icon-s-flag"></i>新人入队</el-menu-item
            > -->
          </el-menu>
        </el-aside>
        <el-main style="height: 800px">
          <el-header
            style="text-align: left; font-size: 12px; line-height: 60px margin-bottom:30px"
          >
            <el-row>
              <el-col :span="4" style="padding-top: 20px">
                <Breadcrumb></Breadcrumb>
              </el-col>
              <el-col :span="2" :offset="16">
                <div class="t" @click="signIn">
                  <i class="el-icon-s-flag"></i>
                  &ensp;签到
                </div>
              </el-col>
              <el-col :span="2">
                <div class="t" @click="signOut">
                  <i class="el-icon-s-promotion"></i>
                  &ensp;签退
                </div>
              </el-col>
            </el-row>
          </el-header>
          <!-- <Main :tableData="Data"></Main> -->
          <div style="margin-top: 30px"><router-view></router-view></div>
        </el-main>
      </el-container>
    </el-container>
    <!-- 弹出的修改密码的弹窗 -->
    <el-dialog title="修改密码" :visible.sync="dialogFormVisible" width="33%">
      <el-form
        :model="ruleForm"
        status-icon
        :rules="rules"
        ref="ruleForm"
        label-width="100px"
        class="demo-ruleForm"
      >
        <el-form-item label="密码" prop="pass">
          <el-input
            type="password"
            v-model="ruleForm.pass"
            autocomplete="off"
            style="width='300px'"
          ></el-input>
        </el-form-item>
        <el-form-item label="确认密码" prop="checkPass">
          <el-input
            type="password"
            v-model="ruleForm.checkPass"
            autocomplete="off"
          ></el-input>
        </el-form-item>

        <el-form-item>
          <el-button type="primary" @click="submitForm('ruleForm')"
            >提交</el-button
          >
          <el-button @click="resetForm('ruleForm')">重置</el-button>
        </el-form-item>
      </el-form>
    </el-dialog>

    <!-- 弹出的人脸注册弹窗 -->
    <div class="faceScan" v-if="faceScan">
      <div class="mask"></div>
      <div class="pop">
        <span
          style="
            font-family: 'Britannic Bold', 'Britannic';
            font-size: 26px;
            color: #3bc5bb;
          "
        >
          CSI员工
        </span>
        <span style="color: #1d4474; font-size: 26px"></span>
        <span style="color: #ff9a4c; font-size: 26px">之家</span>
        <div
          style="
            font-family: 'Britannic Bold', 'Britannic';
            font-size: 12px;
            color: #3bc5bb;
          "
        >
          请将面部置于摄像头前
        </div>
        <div id="media">
          <video
            id="video"
            ref="video"
            width="100%"
            height="300"
            autoplay
          ></video>
        </div>
        <el-button
          type="primary"
          @click="photo"
          style="position: absolute; bottom: 20px; left: 65px"
        >
          注册
        </el-button>
        <el-button
          type="primary"
          @click="faceScanClose"
          style="position: absolute; bottom: 20px; right: 65px"
        >
          取消
        </el-button>
      </div>
    </div>
    <canvas
      ref="canvas"
      width="300"
      height="200"
      style="display: none"
    ></canvas>
  </div>
</template>

<script>
import MyNowTime from "@/components/MyNowTime.vue";
import Breadcrumb from "@/components/Breadcrumb.vue";
import About from "@/components/About.vue";

export default {
  components: { MyNowTime, Breadcrumb, About },
  name: "home",
  data() {
    //修改密码模块：此处即表单发送之前验证
    var validatePass = (rule, value, callback) => {
      if (value === "") {
        callback(new Error("请输入密码"));
      } else {
        if (this.ruleForm.checkPass !== "") {
          this.$refs.ruleForm.validateField("checkPass");
        }
        callback();
      }
    };
    var validatePass2 = (rule, value, callback) => {
      if (value === "") {
        callback(new Error("请再次输入密码"));
      } else if (value !== this.ruleForm.pass) {
        callback(new Error("两次输入密码不一致!"));
      } else {
        callback();
      }
    };

    return {
      username: "",
      dialogFormVisible: false, //弹出的密码修改表单
      ruleForm: {
        pass: "",
        checkPass: "",
      },
      //修改密码的表单规则
      rules: {
        pass: [{ validator: validatePass, trigger: "blur" }],
        checkPass: [{ validator: validatePass2, trigger: "blur" }],
      },
      //人脸注册
      faceScan: false,
      faceImg: { image: "" },
      //是否已经签到
      isSignIn: false,
    };
  },
  methods: {
    // 退出事件
    logout() {
      this.$confirm("确定退出员工之家?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "info",
      })
        .then(() => {
          // this.$store.dispatch('FedLogOut')
          // this.$store.commit('SET_PERMS', '')
          window.sessionStorage.clear();
          window.localStorage.clear();
          this.$message({
            type: "success",
            message: "退出成功!",
          });
          setTimeout(() => {
            location.reload(); // 强制刷新
          }, 1000);
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消退出",
          });
        });
    },
    //修改密码
    upDatePassword() {
      this.dialogFormVisible = true; //弹出修改密码的表单
    },

    submitForm(formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          this.$request
            .post("securityUser/update", {
              password: this.ruleForm.checkPass,
            })
            .then((res) => {
              if (res.data.obj) {
                this.$message.success("修改成功");
                this.dialogFormVisible = false;
              } else {
                this.$message.error("修改失败");
                this.reset();
              }
            });
        } else {
          console.log("error submit!!");
          return false;
        }
      });
    },
    resetForm(formName) {
      this.$refs[formName].resetFields();
    },
    //签到签退
    signIn() {
      if(window.sessionStorage.getItem("sign-in") == "yes") {
        this.$message.info("你已经签到过了");
      }else {
        this.$request.get("sign-in/signIn").then((res) => {
          this.$message.success(res.data.obj);
          window.sessionStorage.setItem("sign-in", "yes");
        });
      }
    },
    signOut() {
      if(window.sessionStorage.getItem("sign-out") == "yes") {
        this.$message.info("你已经签退过了");
      }else{
        this.$request.get("sign-in/signOut").then((res) => {
          this.$message.success(res.data.obj);
          window.sessionStorage.setItem("sign-out", "yes");
        });
      }
    },
    //查询当前用户是否签到
    querySignIn() {
      this.$request.get("sign-in/queryByEmployeeId").then((res) => {
        if (res.data.obj == "true") {
          this.isSignIn = true;
        }
      });
    },
    //打开摄像头
    faceScanOpen() {
      this.faceScan = true;
      // H5调用电脑摄像头API
      navigator.mediaDevices
        .getUserMedia({
          audio: false, //开启音频
          video: true, //开启视频
        })
        .then((success) => {
          var videoTracks = success.getVideoTracks();
          // console.log(success);
          // console.log(videoTracks);
          // 摄像头开启成功
          this.$refs["video"].srcObject = success;
          this.isCameraFlag = false;
          // 实时拍照效果
          this.$refs["video"].play();
        })
        .catch(() => {
          console.error("摄像头开启失败，请检查摄像头是否可用！");
          this.isCameraFlag = true;
        });
    },
    photo() {
      // 把当前视频帧内容渲染到canvas上
      let ctx = this.$refs["canvas"].getContext("2d");
      ctx.drawImage(this.$refs["video"], 0, 0, 320, 240);
      //void ctx.drawImage(image, dx, dy, dWidth, dHeight);
      /* dx  image的左上角在目标canvas上 X 轴坐标。dWidth可选image在目标canvas上绘制的宽度。 允许对绘制的image进行缩放。 如果不说明， 在绘制时image宽度不会缩放。 */
      /**------------后面是下载功能----------*/
      // 转base64格式、图片格式转换、图片质量压缩---支持两种格式image/jpeg+image/png
      let imgBase64 = this.$refs["canvas"].toDataURL("image/jpeg", 0.7);
      // 由字节转换为KB 判断大小
      let str = imgBase64.replace("data:image/jpeg;base64,", "");
      console.log(str);

      //测试用
      // this.faceImg.image = xxx;
      //正式使用时
      this.faceImg.image = str;
      let strLength = str.length;
      let fileLength = parseInt(strLength - (strLength / 8) * 2); // 图片尺寸  用于判断  尺寸过大会导致请求头过长
      let size = (fileLength / 1024).toFixed(2);
      console.log(size); // 上传拍照信息  调用接口上传图片 .........
      // 保存到本地;
      // let ADOM = document.createElement("a");
      // ADOM.href = this.headImgSrc;
      // ADOM.download = new Date().getTime() + ".jpeg";
      // ADOM.click();

      this.$request
        .post("/securityUser/addFace", {
          username: this.username,
          image: this.faceImg,
        })
        .then((res) => {
          let obj = res.data.obj;
          if (res.data.obj) {
            this.$message(obj);
            this.faceScanClose(); //关闭摄像头
          }
        });
    },
    //关闭摄像头
    faceScanClose() {
      this.faceScan = false;
      if (!this.$refs["video"].srcObject) return;
      let stream = this.$refs["video"].srcObject;
      let tracks = stream.getTracks();
      tracks.forEach((track) => {
        track.stop();
      });
      this.$refs["video"].srcObject = null;
      this.isCameraFlag = true;
    },
  },
  mounted() {
    this.username = window.sessionStorage.getItem("username");
  },
};
</script>

<style scoped>
a {
  color: #333;
  text-decoration: none;
}
.el-header {
  background-color: rgb(42, 53, 66);
  color: #fff;
  line-height: 60px;
}

.el-aside {
  color: #333;
}
.el-col {
  /* background-color: #fff; */
  color: #fff;
}
i {
  font-size: 18px;
}
.el-input {
  width: 400px;
}

.mask {
  background-color: rgba(0, 0, 0, 0.7);
  position: fixed;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  z-index: 1;
}
.pop {
  position: fixed;
  top: 100px;
  left: 50%;
  z-index: 2;
  width: 300px;
  height: 400px;
  overflow: hidden;
  margin: 5% auto 0 -150px;
  padding: 20px;
  box-shadow: 0 -15px 30px #fff;
  border-radius: 20px;
}

#media {
  width: 100%;
  height: 250px;
  margin: 10px auto 0;
  border-radius: 30px;
  overflow: hidden;
  opacity: 0.7px;
}
</style>
